/*
 * Created on Sun Oct 01 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';
import type {
  UploadFileParam,
  UploadFileResult,
  GetFileParam,
  GetFileResult,
} from '../../types';

import { createError } from '../../utils/ErrorUtils';
import { ErrorCode } from '../../constants';
import { File } from '../../db/models';

import {
  uploadStrategy,
} from './strategy';

class FileService {
  async upload(param: UploadFileParam): Promise<UploadFileResult> {
    if (!param.path) {
      throw createError(400, '缺少路径', ErrorCode.REQUIRE_PATH);
    }

    if (!param.mimeType) {
      throw createError(400, '缺少类型', ErrorCode.REQUIRE_MIME_TYPE);      
    }
    
    let result = await uploadStrategy.upload(param);

    return result;
  }

  async getFile(param: GetFileParam): Promise<GetFileResult> {
    if (!param.fid) {
      throw createError(400, '缺少文件id', ErrorCode.REQUIRE_FID);
    }

    let doc = await File.findById(param.fid).exec();
    if (!doc) {
      throw createError(404, '文件不存在', ErrorCode.FILE_NOT_FOUNT);
    }

    return {
      fid: doc.id,
      uri: doc.uri,
      mimeType: doc.mimeType,
      md5: doc.md5
    }
  }
}

export default new FileService();
